package com.lic.license.controller;


import com.lic.license.core.License;
import com.lic.license.manager.CustomLicenseManager;
import com.lic.license.param.ComputerParam;
import com.lic.license.service.impl.LicenseCreate;
import com.lic.system.common.Result;
import com.lic.system.service.LicenseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.MessageFormat;


/**
 * 用于生成证书文件，不能放在给客户部署的代码里
 */
@RestController
@RequestMapping("/license")
@Slf4j
public class LicenseCreateController {

    /**
     * 系统默认证书生成路径
     */
    @Value("${license.licensePath}")
    private String licensePath;
    /**
     * 证书subject
     */
    @Value("${license.subject}")
    private String subject;
    /**
     * 私钥别称
     */
    @Value("${license.privateAlias}")
    private String privateAlias;
    /**
     * 访问私钥库的密码
     */
    @Value("${license.storePass}")
    private String storePass;
    /**
     * 私钥的密码
     */
    @Value("${license.keyPass}")
    private String keyPass;
    /**
     * 私钥存储路径
     */
    @Value("${license.privateKeysStorePath}")
    private String privateKeysStorePath;

    /**
     * 获取服务器硬件信息
     */
    @RequestMapping(value = "/getServerInfos")
    public ComputerParam getServerInfos() {
        ComputerParam serverInfos = CustomLicenseManager.getServerInfos();
        return serverInfos;
    }

    @Autowired
    LicenseService licenseService;

    /**
     * 生成证书
     *
     * @param param 生成证书需要的参数，
     */
    @PostMapping("/generateLicense")
    public Result generateLicense(@RequestBody License param) {
        try {
            param.setSubject(subject);
            param.setPrivateAlias(privateAlias);
            param.setKeyPass(keyPass);
            param.setStorePass(storePass);
            param.setPrivateKeysStorePath(privateKeysStorePath);
            LicenseCreate licenseCreator = new LicenseCreate(licenseService);
            licenseCreator.setParam(param);
            licenseCreator.generateLicense();
            return Result.ok("证书生成成功");
        } catch (Exception e) {
            log.error(MessageFormat.format("证书生成失败：{0}", param), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取lic文件
     *
     * @param response
     * @param companyName
     */
    @GetMapping("/getLicenseFile")
    public void getLicenseFile(HttpServletResponse response, String companyName) {
        String s = "../license/" + companyName;
        String path = s + "/license.lic";
        //设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType("application/force-download");
        //设置文件头：最后一个参数是设置下载文件名（设置编码格式防止下载的文件名乱码）
        response.setHeader("Content-Disposition", "attachment;filename=" + licensePath);
        ServletOutputStream out = null;
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(path));
            byte[] buffer = new byte[100];
            out = response.getOutputStream();
            int os = 0;
            while ((os = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, os);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                out.flush();
            } catch (IOException e) {
                System.out.println("文件流不存在");
                e.printStackTrace();
            }
        }

    }


}
